package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"

	"github.com/pinpoint-apm/pinpoint-go-agent"
	pphttp "github.com/pinpoint-apm/pinpoint-go-agent/plugin/http"
)

func index(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "hello world2")
}

var datakitURL, datakitPort, hostPort string

func main() {
	datakitURL = os.Getenv("DATAKIT_HOST")
	datakitPort = os.Getenv("DATAKIT_PORT")

	if len(datakitURL) == 0 {
		fmt.Println("datakit URL is empty")
		return
	}

	if len(datakitPort) == 0 {
		fmt.Println("datakit port is empty")
		return
	}

	hostPort = net.JoinHostPort(datakitURL, datakitPort)
	fmt.Println("host = " + hostPort)

	// configPath, err := getConfigFullPath("pinpoint-config.yaml")
	// if err != nil {
	// 	fmt.Println(err)
	// 	return
	// }
	// fmt.Println("configPath = " + configPath)

	port, err := strconv.Atoi(datakitPort)
	if err != nil {
		fmt.Println(err)
		return
	}

	opts := []pinpoint.ConfigOption{
		pinpoint.WithAppName("TraceWebRequest"),
		pinpoint.WithAgentId("TraceWebRequestAgent"),
		pinpoint.WithCollectorHost(datakitURL),
		pinpoint.WithCollectorAgentPort(port),
		pinpoint.WithCollectorSpanPort(port),
		pinpoint.WithCollectorStatPort(port),
	}
	cfg, _ := pinpoint.NewConfig(opts...)
	agent, err := pinpoint.NewAgent(cfg)
	if err != nil {
		log.Fatalf("pinpoint agent start fail: %v", err)
	}
	defer agent.Shutdown()

	http.HandleFunc("/", pphttp.WrapHandlerFunc(index))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println(err)
		return
	}
}

// func getConfigFullPath(configName string) (string, error) {
// 	exePath, err := os.Executable()
// 	if err != nil {
// 		return "", nil
// 	}
// 	return filepath.Join(filepath.Dir(exePath), configName), nil
// }
